﻿using System;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco.cms.businesslogic.media;
using System.IO;
using System.Text.RegularExpressions;


namespace Decode.Umb.Pixlr
{
	public class pixlrDataEditor : UpdatePanel, umbraco.interfaces.IDataEditor
	{
		private umbraco.interfaces.IData _data;
		private string editorType;
		private string _pixlrLinkClientID;

		public pixlrDataEditor(umbraco.interfaces.IData data, string editorTypeSetting)
		{
			_data = data;
			editorType = editorTypeSetting;
		}


		public virtual bool TreatAsRichTextEditor
		{
			get { return false; }
		}

		public bool ShowLabel
		{
			get { return true; }
		}

		public Control Editor { get { return this; } }


		public void Save()
		{
			this._data.Value = "";
		}

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			PixlrLink();
		}

		protected void PixlrLink(bool saveAsNew = false)
		{
			// media id
			int mediaId;
			if (!int.TryParse(HttpContext.Current.Request.QueryString["id"], out mediaId))
				return;

			// get media
			Media m = new Media(mediaId);
			if (m.Id == 0)
				return;

			// exit if no image is selected
			if (m.getProperty("umbracoFile") == null || String.IsNullOrEmpty(m.getProperty("umbracoFile").Value.ToString()))
				return;

      string imageTitle = CleanImageTitle(m.Text);
      string mediaEditedName = string.Concat(imageTitle, " - edited");

			// pixlr settings
			string rootUrl = Paths.RootUrl;
			string umbracoUrl = string.Concat(rootUrl, VirtualPathUtility.ToAbsolute(ConfigurationManager.AppSettings["umbracoPath"]));
      string imageUrl = string.Concat(rootUrl, m.getProperty("umbracoFile").Value.ToString(), "?r", DateTime.Now.ToString("yyyyMMddHHmmss")); // add unique data to avoid pixlr having cached an old image
			string referer = HttpContext.Current.Request.Url.Host;
			string exitUrl = string.Concat(umbracoUrl, "/plugins/pixlr/save.aspx?close=1");
            string saveMethod = "GET"; // "POST";
			string mediaKey = Decode.Umb.Hash.GetMediaMd5Sum(m); // add hashed key for security
			string saveUrl = string.Concat(
				umbracoUrl,
				"/plugins/pixlr/save.aspx?id=",
				mediaId,
				"|",
				mediaKey,
				"|",
				(saveAsNew ? "1" : "0"),
				"|",
				mediaEditedName
			);
			string pixlrJs = string.Concat(umbracoUrl, "/plugins/pixlr/pixlr_minified.js");

			// default link text
			string linkText = umbraco.ui.GetText("pixlrLink");
			if (linkText.Equals("[pixlrLink]"))
				linkText = "Edit image";

			string saveAsNewText = umbraco.ui.GetText("pixlrSaveAsNew");
			if(saveAsNewText.Equals("[pixlrSaveAsNew]"))
				saveAsNewText = "Save as new?";

			string newMediaNameText = umbraco.ui.GetText("pixlrNewMediaName");
			if (newMediaNameText.Equals("[pixlrNewMediaName]"))
				newMediaNameText = "New media name: ";

			TextBox tbNewName = null;
			Panel pnlNewName = base.ContentTemplateContainer.FindControl("pnlNewName") as Panel;
			if (pnlNewName != null)
				tbNewName = pnlNewName.FindControl("tbNewName") as TextBox;

			// pixlr link
			Literal pixlrLink = base.ContentTemplateContainer.FindControl("lnkPixlrLink") as Literal;
			if (pixlrLink == null)
			{
				pixlrLink = new Literal();
				pixlrLink.ID = "lnkPixlrLink";
				base.ContentTemplateContainer.Controls.Add(pixlrLink);
			}
			SetPixlrLinkText(imageUrl, imageTitle, referer, exitUrl, saveMethod, saveUrl, linkText, pixlrLink);

			CheckBox cbSaveAsNew = base.ContentTemplateContainer.FindControl("cbSaveAsNew") as CheckBox;
			if (cbSaveAsNew == null)
			{
				cbSaveAsNew = new CheckBox();
				cbSaveAsNew.ID = "cbSaveAsNew";
				cbSaveAsNew.Text = saveAsNewText;
				cbSaveAsNew.CheckedChanged += new EventHandler(cbSaveAsNew_CheckedChanged);
				cbSaveAsNew.AutoPostBack = true;
				ScriptManager.GetCurrent(Page).RegisterAsyncPostBackControl(cbSaveAsNew);
				base.ContentTemplateContainer.Controls.Add(cbSaveAsNew);
			}

			if (pnlNewName == null)
			{
				pnlNewName = new Panel();
				pnlNewName.ID = "pnlNewName";
				pnlNewName.Style.Add("margin-left", "10px;");

				Label lblNewName = new Label();
				lblNewName.Text = newMediaNameText;
				pnlNewName.Controls.Add(lblNewName);

				tbNewName = new TextBox();
				tbNewName.ID = "tbNewName";
				tbNewName.Text = mediaEditedName;
				pnlNewName.Controls.Add(tbNewName);

				base.ContentTemplateContainer.Controls.Add(pnlNewName);
			}

			pnlNewName.Style["display"] = "none";
			if (saveAsNew)
				pnlNewName.Style["display"] = "inline";

			// register pixlr script file
			ScriptManager.RegisterClientScriptInclude(this.Page, this.GetType(), "pixlr", pixlrJs);

			string script = @"
							var pixlrLink;
							var originalUrl;
							$(function() {
								var textbox = $('#" + tbNewName.ClientID + @"');
								pixlrLink = $('#" + _pixlrLinkClientID + @"')[0];
								originalUrl = pixlrLink.getAttributeNode('onclick').value;
								textbox.change(function() {
									if(textbox.val() != '')
										pixlrLink.getAttributeNode('onclick').value = originalUrl.replace('" + mediaEditedName + @"', textbox.val().replace('|', ''));
								});
							});";
			ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "pixlr_tbChanged", script, true);
		}

		void cbSaveAsNew_CheckedChanged(object sender, EventArgs e)
		{
			CheckBox cbSaveAsNew = sender as CheckBox;
			PixlrLink(cbSaveAsNew.Checked);
		}

    private string CleanImageTitle(string s)
    {
      return Regex.Replace(HttpUtility.HtmlDecode(s), @"[^A-Za-z0-9_]", "", RegexOptions.IgnoreCase);
    }

    private string EncodeApostrophes(string s)
    {
      return s.Replace("'", "%27");
    }

		void SetPixlrLinkText(string imageUrl, string imageTitle, string referer, string exitUrl, string saveMethod, string saveUrl, string linkText, Literal pixlrLink)
		{
			_pixlrLinkClientID = string.Concat(this.ClientID, "pixlrLink");
			pixlrLink.Text = String.Format("<a id=\"{8}\" href=\"javascript:void(0)\" onclick=\"javascript:pixlr.window({{" +
											"image:'{0}'," +
											"title: '{1}'," +
											"method: '{2}'," +
											"service: '{3}'," +
											"referer: '{4}'," +
											"exit: '{5}'," +
											"target: '{6}'," +
											"credentials: true, " +
											"locktarget: true " +
											"}});\">Open image in external editor</a><br />",
                      EncodeApostrophes(imageUrl),
                      EncodeApostrophes(imageTitle),
											EncodeApostrophes(saveMethod),
											EncodeApostrophes(editorType),
											EncodeApostrophes(referer),
											EncodeApostrophes(exitUrl),
											EncodeApostrophes(saveUrl),
											EncodeApostrophes(linkText),
											EncodeApostrophes(_pixlrLinkClientID));
		}
	}
}